/**
 * Created by oneminute on 7/16/14.
 */
// I hate making wheels
exports.createExpress = function () {
    var express = require('express'),
        extend = require('extend'),
        URL = require('url'),
        qs = require('querystring'),
        router = express.Router(),
        sideEffects = { session: {}, model: {} },
        defaultRequest, defaultResponse;


    // limited subset for now
    return {
        'all': function () {
            router.all.apply(router, Array.prototype.slice.apply(arguments));
        },
        'route': function () {
            return router.route.apply(router, Array.prototype.slice.apply(arguments));
        },
        'invoke': function (req, res, next) {
            var endFn = res.end;
            res.end = function (_data, _encoding) {
                endFn(_data, _encoding);
                next(JSON.parse(res._getData()));
            };
            router.handle(req, res);
        },
        'path': function () {
            return route || '/';
        },
        'makeAssertionCallback': function (callback, assertions) {
            return function (err, sideEffects) {
                try {
                    assertions(err, sideEffects);
                    callback();
                } catch (e) {
                    callback(e);
                }
            };
        },
        'makeRequest': function (getMap) {
            var requestObject = Object.create(null);
            requestObject.get = function (property) {
                return getMap[property];
            };

            Object.defineProperty(requestObject, 'session', {
                get: function () {
                    return sideEffects.session;
                },
                set: function (newValue) {
                    sideEffects.session = newValue;
                }
            });

            defaultRequest = requestObject;

            return requestObject;
        },
        'makeResponse': function (callback) {
            defaultResponse = {
                redirect: function (location) {
                    sideEffects.redirect = location;
                    callback(null, sideEffects);
                },
                render: function (viewName, model) {
                    sideEffects.viewName = viewName;
                    sideEffects.model = model;
                    callback(null, sideEffects);
                }
            };
            return defaultResponse;
        }
    };

};

//module.exports = MockExpress;
